package net.jiug.email.service.impl;

import net.jiug.common.config.ConfigEmail;
import net.jiug.common.exception.BadRequestException;
import net.jiug.common.utils.EmailUtils;
import net.jiug.common.web.base.BaseService;
import net.jiug.email.model.Email;
import net.jiug.email.model.EmailContent;
import net.jiug.email.service.EmailService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;

/**
 * @author keffett
 * @date 2018-11-23
 */
@Service
public class EmailServiceImpl extends BaseService implements EmailService {

    /**
     * 当前使用邮箱序号
     */
    private static int currentUseEmailIndex = 0;
    /**
     * 当前邮箱使用次数
     */
    private static int currentUseCount = 0;

    @Resource
    private EmailUtils emailUtils;
    @Resource
    private ConfigEmail configEmail;

    /**
     * 通知
     */
    @Override
    public void notice(EmailContent emailContent) throws Exception {
        try {
            // 邮件标题处理
            String title = StringUtils.isEmpty(emailContent.getTitle()) ? configEmail.getNoticeTitle() : emailContent.getTitle();
            // 邮件内容处理
            String content;
            switch (emailContent.getType()) {
                // 1：简易验证码
                case 1:
                    content = "您的验证码是：" + emailContent.getContent()
                            + "，此验证码用于" + emailContent.getNote()
                            + "，若非本人操作，请忽略此邮件。";
                    break;
                // 2：标签+内容
                case 2:
                    content = emailContent.getNote() + emailContent.getContent();
                    throw new MessagingException("ggg");
                    //break;
                // 默认：内容不处理
                default:
                    content = emailContent.getContent();
            }
            // 发送邮件
            emailUtils.sendEmail(emailContent.getToEmail(), title, content);

        } catch (MessagingException e){
            currentUseCount=configEmail.getEmailUseThresholdValue();
            String errorMessage = "邮件发送异常！";
            logger.severe(errorMessage);
            e.printStackTrace();
            throw new BadRequestException(errorMessage);
        } finally {
            // 更新当前邮箱账户(使用次数到达使用阈值时进行更新)
            updateCurrentEmailAccount();
        }

    }

    @Override
    public void notice(String content,String email) throws Exception {
        // 发送邮件
        emailUtils.sendEmail(email, configEmail.getNoticeTitle(), content);
        // 更新当前邮箱账户(使用次数到达使用阈值时进行更新)
        updateCurrentEmailAccount();
    }

    /**
     * 更新当前邮箱账户
     */
    @Override
    @Async
    public void updateCurrentEmailAccount() {
        // 使用次数到达使用阈值时进行更新
        if(configEmail.getEmailUseThresholdValue()<=++currentUseCount){
            // 使用次数重置
            currentUseCount=0;
            // 当前使用邮箱序号++/0
            if(configEmail.getEmailList().size()<=++currentUseEmailIndex) currentUseEmailIndex=0;
            // 获取当前使用邮箱
            Email email = configEmail.getEmailList().get(currentUseEmailIndex);
            // 更新邮箱会话连接
            emailUtils.updateSession(email.getHost(),
                    email.getPort(),
                    email.getAccount(),
                    email.getSecretKey(),
                    configEmail.getNick());
        }
    }

}
